<template>
  <div class="attachment-view">
    <component
      :is="size == 'mini' ? 'div' : 'a-card'"
      class="attachment-group"
      :class="{
        'attachment-small': size == 'small',
        'attachment-mini': size == 'mini',
      }"
      :size="size == 'mini' ? 'small' : size"
      v-for="group in groups"
      :key="group.groupName"
    >
      <div class="attachment-group-title">{{ group.groupName }}</div>
      <div class="attachment-group-wrapper">
        <div
          class="attachment-item"
          v-for="(item, itemIndex) in groupAttchments(group.groupName)"
          :key="itemIndex"
        >
          <div class="icon" @click="showPreviewFile(item)">
            <img
              :src="'/api/file/download/' + item.fileId"
              v-if="isImage(item.name)"
            />
            <file-icon v-else :size="36" :name="item.name" />
          </div>
          <div class="filename" @click="showPreviewFile(item)">
            {{ item.name }}
          </div>
          <div class="close" v-if="!readonly" @click="removeItem(item)">
            <CloseOutlined />
          </div>
        </div>
        <a-upload
          v-model:file-list="fileList"
          :multiple="true"
          name="file"
          :showUploadList="false"
          :customRequest="uploadRequest"
          @change="(e) => onUploadChanged(group.groupName, e)"
          v-if="!readonly && fixed"
        >
          <div
            class="attachment-item add-item"
            :loading="uploading"
            v-show="
              !maxCount || maxCount > groupAttchments(group.groupName).length
            "
          >
            <UploadOutlined />
            添加文件
          </div>
        </a-upload>
      </div>
      <div class="attachment-action" v-if="!readonly && !fixed">
        <a-upload
          v-model:file-list="fileList"
          :multiple="true"
          name="file"
          :showUploadList="false"
          :customRequest="uploadRequest"
          @change="(e) => onUploadChanged(group.groupName, e)"
          v-show="
            !maxCount || maxCount > groupAttchments(group.groupName).length
          "
        >
          <a-button :loading="uploading" :size="size">
            <UploadOutlined />
            添加文件
          </a-button>
        </a-upload>
      </div>
    </component>
  </div>

  <preview-file
    v-model:visible="previewModel.visible"
    :id="previewModel.id"
    :fileName="previewModel.fileName"
    v-if="previewModel.visible"
  />
</template>

<script lang="ts" setup>
import { AttachmentItemDto } from "@/api/models";
import { computed, onMounted, ref, watch } from "vue";
import { useDataStore } from "@/store";
import configApi from "@/api/resource/attachmentConfig";
import uploadApi from "@/api/resource/fileResource";
import { storeToRefs } from "pinia";
import { UploadFileResourceInputDto } from "@/api/resource/types";
import { UploadOutlined, CloseOutlined } from "@ant-design/icons-vue";
import type { UploadChangeParam } from "ant-design-vue";
import PreviewFile from "@/components/preview-file/Index.vue";

const dataStore = useDataStore();
const { attachmentConfigItems } = storeToRefs(dataStore);

/**
 * 附件管理输入框
 */
type AttachmentInputProp = {
  bucketName: string;
  dir?: string;
  bussinessType: string;
  readonly: boolean;
  attachments: Array<AttachmentItemDto>;
  size?: "small" | "normal" | "mini";
  fixed?: boolean;
  maxCount?: number;
};

const props = withDefaults(defineProps<AttachmentInputProp>(), {
  readonly: false,
  maxCount: 0,
});

const fileList = ref([]);

const previewModel = ref<{ visible: boolean; id: string; fileName: string }>({
  id: "",
  fileName: "",
  visible: false,
});

const groupAttchments = (groupName: string) => {
  return (
    props.attachments.filter((x) => x.groupName == groupName || !groupName) ||
    []
  );
};

/**
 * 判断是否为图片
 * @param name
 */
const isImage = (name: string) => {
  if (!name) {
    return false;
  }
  let ext = name.substring(name.lastIndexOf("."));
  return (
    [".jpg", ".png", ".tif", ".bmp", ".svg", ".gif"].findIndex(
      (x) => x == ext?.toLocaleLowerCase()
    ) != -1
  );
};
/**
 * 附件分组数据
 */
const groups = computed(() => {
  if (props.bussinessType) {
    let items = attachmentConfigItems.value.filter(
      (x) => x.bussinessType == props.bussinessType
    );
    return items.length
      ? items
      : [
          {
            bussinessType: "",
            groupName: "附件资料",
            defineFields: [],
            maxLength: 0,
          },
        ];
  } else {
    return [
      {
        bussinessType: "",
        groupName: "附件资料",
        defineFields: [],
        maxLength: 0,
      },
    ];
  }
});

const uploadRequest = (options: any) => {
  let data: UploadFileResourceInputDto = {
    dir: props.dir,
    bucketName: props.bucketName,
    fileName: options.file.name,
    isPublic: false,
    file: options.file,
  };
  uploadApi.upload(data).then((res) => {
    options.onSuccess(res, options.file);
  });
};

const uploading = ref(false);

const onUploadChanged = (groupName, info: UploadChangeParam) => {
  uploading.value = info.file.status == "uploading";
  if (info.file.status === "done") {
    //上传成功
    let res = info.file.response.data;
    props.attachments.push({
      fileId: res.id,
      fileType: res.fileType,
      name: res.fileName,
      groupName: groupName,
      extraProperties: {},
    });
  }
};

const removeItem = (item: AttachmentItemDto) => {
  let index = props.attachments.findIndex((x) => x == item);
  if (index !== -1) {
    props.attachments.splice(index, 1);
  }
};

const showPreviewFile = (item: AttachmentItemDto) => {
  previewModel.value = {
    visible: true,
    id: item.fileId,
    fileName: item.name,
  };
};

onMounted(async () => {
  if (!attachmentConfigItems.value.length) {
    let items = await configApi.getAllList({});
    dataStore.setAllAttachmentConfigItems(items);
  }
});
</script>

<style lang="less" scoped>
.attachment {
  &-group {
    margin-bottom: 10px;

    &-title {
      font-size: 16px;
      color: #0081cc;
    }

    &-wrapper {
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      align-items: flex-start;
      justify-content: start;
    }

    .attachment {
      &-item {
        cursor: pointer;
        position: relative;
        display: flex;
        flex: none;
        align-items: flex-start;
        padding: 10px;
        background: #f9f9f9;
        border: 1px solid #eee;
        border-radius: 5px;
        width: 240px;
        margin: 0 5px 5px 0;

        .icon {
          height: 60px;
          width: 48px;
          margin-right: 5px;
          display: flex;
          justify-content: center;
          align-items: center;

          img {
            max-width: 48px;
            max-height: 48px;
          }
        }

        .filename {
          display: flex;
          flex: 1;
          line-height: 20px;
          align-items: center;
          overflow: hidden;
          min-height: 60px;
          word-break: break-all;
        }

        .close {
          position: absolute;
          z-index: 1;
          right: 0;
          top: 0;
          padding: 5px 10px;
          background: #ff330022;
          color: #777;

          &:hover {
            background: #ff3300;
            color: #fff;
          }
        }
      }

      &-action {
        border-top: 1px dashed #ddd;
        margin-top: 10px;
        padding-top: 10px;
      }

      &-view {
        position: relative;
        min-height: 40px;
      }
    }

    &.attachment-small {
      .attachment {
        &-group-title {
          display: none;
        }

        &-item {
          padding: 5px;
          width: 175px;
          &.add-item {
            width: 120px;
            background: rgba(0, 128, 255, 0.75);

            .icon {
              font-size: 20px;
              color: #fff;
            }
            .filename {
              font-size: 14px;
              color: #fff;
            }
          }

          .close {
            padding: 0 5px;
            height: 18px;
          }
        }
      }
    }

    &.attachment-mini {
      .attachment {
        &-group-title {
          display: none;
        }

        &-item {
          border: 1px solid #ddd;
          padding: 0 5px;
          width: 240px;

          .icon {
            height: 30px;
            width: 24px;

            img {
              max-width: 24px;
              max-height: 24px;
            }
          }

          .filename {
            height: 30px;
            line-height: 30px;
            min-height: 30px;
          }
          &.add-item {
            width: 100px;
            height: 30px;
            background: rgba(0, 128, 255, 0.75);
            justify-content: center;
            color: #fff;
            display: flex;
            align-items: center;
            &:active {
              background: rgba(0, 128, 255, 0.55);
            }
          }

          .close {
            padding: 0 5px;
            height: 18px;
          }
        }
      }
    }
  }
}
</style>
